package com.example.interceptor.config;


import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("执行拦截器类，原有的请求路径为："+request.getRequestURI());
        HttpSession session = request.getSession();
        if(session.getAttribute("username")==null){
            //说明当前用户没有登录
            response.sendRedirect("/login");//跳转到登录页面
            return false;
            //该方法返回true时表示对请求进行放行，即可以继续打开原来请求的资源
            //返回值为false时表示拦截请求，既不能打开原来的网页，一般会跳到一个页面，如登录页面
        }else {
            //当前用户已经登录
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
